const { verifyToken } = require('../utils/jwt');
const ResponseCode = require('../utils/responseCode');

const authMiddleware = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.startsWith('Bearer ') 
      ? authHeader.slice(7)  // Bearer token 格式
      : authHeader;          // 直接传递 token

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '请先登录'
      });
    }

    const decoded = await verifyToken(token);
    if (!decoded) {
      return res.status(401).json({
        code: 401,
        message: 'token已失效，请重新登录'
      });
    }

    req.user = decoded;
    next();
  } catch (error) {
    console.error('认证错误:', error);
    res.status(401).json({
      code: 401,
      message: '认证失败'
    });
  }
};

module.exports = authMiddleware; 